package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.aspectj.weaver.ast.Var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {
    @Autowired
    private WorkspaceService workspaceService;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    /**
     * 根据时间查询营业额数据
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        //当前集合用于存放从begin到end范围内的日期
        List<LocalDate> datalist = new ArrayList<>();
        datalist.add(begin);

        while (!begin.equals(end))
        {
            begin=begin.plusDays(1);
            datalist.add(begin);
        }



        List<Double> turnoverList = new ArrayList<Double>();
        for (LocalDate localDate : datalist) {
            //查询date日期对应的营业额数据，状态为已完成的订单金额合计
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);

            Map map = new HashMap();
            map.put("begin",beginTime);
            map.put("end",endTime);
            map.put("status", Orders.COMPLETED);
            Double turnover = orderMapper.sumByMap(map);
            turnover = turnover == null? 0.00 :turnover;
            turnoverList.add(turnover);
            //select sum(amount) from orders where order_time > ? and order_time <? and status =5
        }

        TurnoverReportVO turnoverReportVO = new TurnoverReportVO();
        turnoverReportVO.setTurnoverList((StringUtils.join(turnoverList,",")));
        turnoverReportVO.setDateList(StringUtils.join(datalist,","));


        return turnoverReportVO;
    }

    /**
     * 查询指定时间区间内的用户数据
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO getUserStastistic(LocalDate begin, LocalDate end) {
        List<LocalDate> datalist = new ArrayList<>();
        datalist.add(begin);

        while (!begin.equals(end))
        {
            begin=begin.plusDays(1);
            datalist.add(begin);
        }

        List<Integer> newUserLIST= new ArrayList<Integer>();
        List<Integer> totalUserLIST= new ArrayList<Integer>();
        for (LocalDate localDate : datalist) {

            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            Map userMap =new HashMap();
            //总用户数量
            userMap.put("end",endTime);
            Integer totalUser = userMapper.countBymap(userMap);
            //新增用户数量
            userMap.put("begin",beginTime);
            Integer newUser = userMapper.countBymap(userMap);

            newUserLIST.add(newUser);
            totalUserLIST.add(totalUser);
        }
        //封装结果数据
        return UserReportVO.builder()
                .dateList(StringUtils.join(datalist,","))
                .totalUserList(StringUtils.join(totalUserLIST,","))
                .newUserList(StringUtils.join(newUserLIST,","))
                .build();
    }

    /**
     * 订单数据统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> datalist = new ArrayList<>();
        datalist.add(begin);

        while (!begin.equals(end))
        {
            begin=begin.plusDays(1);
            datalist.add(begin);
        }
        List<Integer> orderTotalList = new ArrayList();
        List<Integer> orderValidList = new ArrayList();
        //便理解和查询有效订单数和总数
        for (LocalDate date : datalist) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map =new HashMap();
            map.put("begin",beginTime);
            map.put("end",endTime);
            //查询每天订单总数
            Integer ordersTotal = orderMapper.countByMap(map);
            orderTotalList.add(ordersTotal);
            //查询每天有效订单数
            map.put("status",Orders.COMPLETED);
            Integer ordersValid = orderMapper.countByMap(map);
            orderValidList.add(ordersValid);


        }
        System.out.println(orderTotalList);
        Integer totalOrder = orderTotalList.stream().reduce(Integer::sum).get();
        Integer validOrder = orderValidList.stream().reduce(Integer::sum).get();
        Double orderComplication = 0.0;
        if(totalOrder !=0) {
            Double.valueOf(validOrder / totalOrder);
        }


        return OrderReportVO.builder()
                .dateList(StringUtils.join(datalist,","))
                .orderCountList(StringUtils.join(orderTotalList,","))
                .validOrderCountList(StringUtils.join(orderValidList,","))
                .totalOrderCount(totalOrder)
                .validOrderCount(validOrder)
                .orderCompletionRate(orderComplication)
                .build();
    }

    /**
     * 指定时间区间销量前十统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {

        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        List<GoodsSalesDTO> salesTop10 = orderMapper.getSalesTop10(beginTime, endTime);

        List<String> top10Name = salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        String nameOfTop10 = StringUtils.join(top10Name, ",");

        List<Integer> top10Amount = salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String amountOfTop10 = StringUtils.join(top10Amount, ",");

        log.info("销量top10的餐品数量{}",amountOfTop10);
        return SalesTop10ReportVO
                .builder()
                .nameList(nameOfTop10)
                .numberList(amountOfTop10)
                .build();
    }

    /**
     * 导出运营数据报表
     * @param response
     */
    @Override
    public void exportBusinessData(HttpServletResponse response) throws FileNotFoundException {
        //查询数据库，获取数据
        LocalDate dateStart = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);

        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(dateStart, LocalTime.MIN), LocalDateTime.of(dateEnd, LocalTime.MAX));

        //通过POI将数据写入到excel文件中
        FileInputStream fileInputStream = new FileInputStream(new File("E:\\java\\sky-take-out\\sky-server\\src\\main\\resources\\template\\运营数据报表模板.xlsx"));

        try {
            XSSFWorkbook excel = new XSSFWorkbook(fileInputStream);
            //填充数据：时间
            XSSFSheet sheet1 = excel.getSheet("sheet1");

            XSSFRow row = sheet1.getRow(1);
            row.getCell(1).setCellValue("时间:"+dateStart+"至"+dateEnd);

            //填充数据：营业额等
            sheet1.getRow(3).getCell(2).setCellValue(businessData.getTurnover());

            sheet1.getRow(3).getCell(4).setCellValue(businessData.getOrderCompletionRate());

            sheet1.getRow(3).getCell(6).setCellValue(businessData.getNewUsers());

            sheet1.getRow(4).getCell(2).setCellValue(businessData.getValidOrderCount());

            sheet1.getRow(4).getCell(4).setCellValue(businessData.getUnitPrice());

            //填充明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = dateStart.plusDays(i);
                BusinessDataVO businessDataVO = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                row = sheet1.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessDataVO.getTurnover());
                row.getCell(3).setCellValue(businessDataVO.getValidOrderCount());
                row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessDataVO.getUnitPrice());
                row.getCell(6).setCellValue(businessDataVO.getNewUsers());
            }

            //通过输出流将excel文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            //关机资源
            out.close();
            excel.close();
            fileInputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }




    }
}
